home *** CD-ROM | disk | FTP | other *** search
/ STraTOS 1997 April & May / STraTOS 1 - 1997 April & May.iso / CD01 / INTERNET / SITES / LITTLE / P3SRC.ZIP / ATARI / PNG_POV.C < prev    next >
Encoding:
C/C++ Source or Header  |  1997-01-17  |  51.7 KB  |  1,693 lines

  1. /*****************************************************************************
  2. *        png_pov.c
  3. *
  4. *  This module contains the code to read and write the PNG output file
  5. *
  6. *  from Persistence of Vision(tm) Ray Tracer
  7. *  Copyright 1996 Persistence of Vision Team
  8. *---------------------------------------------------------------------------
  9. *  NOTICE: This source code file is provided so that users may experiment
  10. *  with enhancements to POV-Ray and to port the software to platforms other
  11. *  than those supported by the POV-Ray Team.  There are strict rules under
  12. *  which you are permitted to use this file.  The rules are in the file
  13. *  named POVLEGAL.DOC which should be distributed with this file. If
  14. *  POVLEGAL.DOC is not available or for more info please contact the POV-Ray
  15. *  Team Coordinator by leaving a message in CompuServe's Graphics Developer's
  16. *  Forum.  The latest version of POV-Ray may be found there as well.
  17. *
  18. * This program is based on the popular DKB raytracer version 2.12.
  19. * DKBTrace was originally written by David K. Buck.
  20. * DKBTrace Ver 2.0-2.12 were written by David K. Buck & Aaron A. Collins.
  21. *
  22. * Original patch copyright 1995 Andreas Dilger 
  23. * Updated for POV 3.0 by Tim Wegner, August 1995.
  24. * Updated to allow resuming by Andreas Dilger, Sept 1995.
  25. * Updated to support Alpha channel input/output by Andreas Dilger, Sept 1995
  26. * Updated to set the flush distance based on the file buffer size, Dec 1995
  27. * Updated to use the libpng 0.87 messaging functions, Dec 1995
  28. * Updated to use the libpng 0.89 structure interface, Jun 1996
  29. *
  30. *****************************************************************************/
  31.  
  32. /*****************************************************************************
  33. *  This code requires the use of libpng, Group 42's PNG reference library.
  34. *  libpng is  Copyright (c) 1995 Guy Eric Schalnat, Group 42, Inc.
  35. *
  36. *  This code also requires the use of Zlib,
  37. *  Zlib is Copyright (C) 1995 Jean-loup Gailly and Mark Adler
  38. *
  39. *  The latest version of these libraries are available at ftp.uu.net as
  40. *
  41. *  /graphics/png/libpngXX.tar.gz.
  42. *  /archiver/zlib/zlib-XX.tar.gz.
  43. *
  44. *  where XX is the latest version of the library.
  45. *
  46. *****************************************************************************/
  47.  
  48. #include "frame.h"
  49. #include "povproto.h"
  50. #include "povray.h"
  51. #include "optout.h"
  52. #include <png.h>
  53. #include "png_pov.h"
  54.  
  55.  
  56.  
  57. /*****************************************************************************
  58. * Local preprocessor defines
  59. ******************************************************************************/
  60.  
  61. /* Number of scanlines between output flushes, and hence the maximum number of
  62.  * lines lost for an interrupted render.  Note that making it much smaller
  63.  * than about 10 for a 640x480 image will noticably degrade compression.
  64.  * If a very small buffer is specified, we don't want to flush more than once
  65.  * every 10 lines or so (assuming a 2:1 compression ratio).
  66.  */
  67. /*
  68. #define FLUSH_DIST 10
  69. #define FLUSH_DIST (*width >= 640 ? 10 : 6400 / *width)
  70. */
  71. #define FLUSH_DIST ((opts.Options & BUFFERED_OUTPUT && \
  72.                      handle->buffer_size > (*width * png_stride * 5)) ? \
  73.                     (handle->buffer_size / (*width * png_stride)): \
  74.                     (*width >= 640 ? 10 : 6400 / *width))
  75.  
  76. #define NTEXT 15     /* Maximum number of tEXt comment blocks */
  77. #define MAXTEXT 1024 /* Maximum length of a tEXt message */
  78.  
  79.  
  80.  
  81. /*****************************************************************************
  82. * Local typedefs
  83. ******************************************************************************/
  84.  
  85.  
  86.  
  87. /*****************************************************************************
  88. * Local variables
  89. ******************************************************************************/
  90.  
  91. static png_struct *png_ptr  = NULL;
  92. static png_info   *info_ptr = NULL;
  93. static png_struct *o_png_ptr  = NULL;
  94. static png_byte   *row_ptr  = NULL;
  95. static int        png_stride;
  96. static char       tmp_fname[FILE_NAME_LENGTH];
  97. static FILE       *tmp_fp = NULL;
  98.  
  99.  
  100.  
  101. /*****************************************************************************
  102. * Static functions
  103. ******************************************************************************/
  104.  
  105. static int Open_Png_File PARAMS((FILE_HANDLE *handle, char *name, int *width, int *height, int buffer_size, int mode));
  106. static void Write_Png_Line PARAMS((FILE_HANDLE *handle, COLOUR *line_data, int line_number));
  107. static int Read_Png_Line PARAMS((FILE_HANDLE *handle, COLOUR *line_data, int *line_number));
  108. static void Close_Png_File PARAMS((FILE_HANDLE *handle));
  109.  
  110.  
  111. /* These are replacement error and warning functions for the libpng code */
  112. static void png_pov_err PARAMS((png_struct *png_ptr, char *msg));
  113. static void png_pov_warn PARAMS((png_struct *png_ptr, char *msg));
  114.  
  115. /* This is an internal function for libpng */
  116. extern void png_write_finish_row PARAMS((png_struct *png_ptr));
  117.  
  118. /*****************************************************************************
  119. *
  120. * FUNCTION      : Get_Png_File_Handle
  121. *
  122. * ARGUMENTS     : none
  123. *
  124. * MODIFIED ARGS : none
  125. *
  126. * RETURN VALUE  : File Handle
  127. *
  128. * AUTHOR        : Andreas Dilger
  129. *
  130. * DESCRIPTION
  131. *
  132. *   Allocate memory for and setup file handle for PNG file.
  133. *
  134. * CHANGES
  135. *
  136. *   Updated for POV-Ray 3.X - [TIW]
  137. *
  138. ******************************************************************************/
  139.  
  140. FILE_HANDLE *Get_Png_File_Handle()
  141. {
  142.   FILE_HANDLE *handle;
  143.   
  144.   handle = (FILE_HANDLE *)POV_MALLOC(sizeof(FILE_HANDLE), "PNG file handle");
  145.  
  146.   handle->Open_File_p  = Open_Png_File;
  147.   handle->Write_Line_p = Write_Png_Line;
  148.   handle->Read_Line_p  = Read_Png_Line;
  149.   handle->Read_Image_p = Read_Png_Image;
  150.   handle->Close_File_p = Close_Png_File;
  151.   
  152.   handle->buffer_size = 0;
  153.   
  154.   handle->file = NULL;
  155.   handle->buffer = NULL;
  156.   
  157.   return (handle);
  158. }
  159.  
  160.  
  161. /*****************************************************************************
  162. *
  163. * FUNCTION      : png_pov_warn
  164. *
  165. * ARGUMENTS     : png_struct *png_ptr; char *msg;
  166. *
  167. * MODIFIED ARGS :
  168. *
  169. * RETURN VALUE  :
  170. *
  171. * AUTHOR        : Andreas Dilger
  172. *
  173. * DESCRIPTION
  174. *
  175. *   Prints an warning message using the POV I/O functions.  This uses the
  176. *   png io_ptr to determine whether error messages should be printed or
  177. *   not.
  178. *
  179. * CHANGES
  180. *
  181. ******************************************************************************/
  182. static void png_pov_warn(png_ptr, msg)
  183. png_struct *png_ptr;
  184. char *msg;
  185. {
  186.   if (png_get_error_ptr(png_ptr))
  187.     Warning(0.0,"libpng: %s\n",msg);
  188. }
  189.  
  190.  
  191. /*****************************************************************************
  192. *
  193. * FUNCTION      : png_pov_err
  194. *
  195. * ARGUMENTS     : png_struct *png_ptr; char *msg;
  196. *
  197. * MODIFIED ARGS :
  198. *
  199. * RETURN VALUE  :
  200. *
  201. * AUTHOR        : Andreas Dilger
  202. *
  203. * DESCRIPTION
  204. *
  205. *   If the png io_ptr is TRUE, this prints an error message using the POV
  206. *   I/O function.  It will return to the location of the last setjmp call
  207. *   for this stream in any case.
  208. *
  209. * CHANGES
  210. *
  211. ******************************************************************************/
  212. static void png_pov_err(png_ptr, msg)
  213. png_struct *png_ptr;
  214. char *msg;
  215. {
  216.   if (png_get_error_ptr(png_ptr))
  217.     Error_Line("libpng: %s\n",msg);
  218.  
  219.   longjmp(png_ptr->jmpbuf,1);
  220. }
  221.  
  222.  
  223. /*****************************************************************************
  224. *
  225. * FUNCTION      : Open_Png_File
  226. *
  227. * ARGUMENTS     : FILE_HANDLE *handle; char *name; int *width; int *height;
  228. *                 int buffer_size; int mode;
  229. *
  230. * MODIFIED ARGS : handle, width, height
  231. *
  232. * RETURN VALUE  : 1 or 0 for success or failure
  233. *
  234. * AUTHOR        : Andreas Dilger
  235. *
  236. * DESCRIPTION
  237. *
  238. *   Open a PNG file and allocate the needed PNG structure buffers
  239. *
  240. * CHANGES
  241. *
  242. *   Updated for POV-Ray 3.X - [TIW]
  243. *   Updated to handle resuming interrupted traces, Sept 1995 - [AED]
  244. *   Updated to output grayscale heightfield if requested - [AED]
  245. *   Updated to allow grayscale and alpha together, Oct 1995 - [AED]
  246. *   Updated to write gamma differently based on file type, Nov 1995 - [AED]
  247. *   Changed temp file name from TEMP_FILE_BASE to scene name, Feb 1996 - [AED]
  248. *   Changed temp file from scene name to path + scene name, Jun 1996 - [AED]
  249. *
  250. ******************************************************************************/
  251.  
  252. static int Open_Png_File(handle, name, width, height, buffer_size, mode)
  253. FILE_HANDLE *handle;
  254. char *name;
  255. int *width;
  256. int *height;
  257. int buffer_size;
  258. int mode;
  259. {
  260.   handle->mode = mode;
  261.   handle->filename = name;
  262.   
  263.   switch (mode)
  264.   {
  265.     case READ_MODE:
  266.     
  267.       Status_Info("\nResuming interrupted trace from %s",handle->filename);
  268.  
  269.       /* Initialize PNG output routines using temporary file name.  We
  270.        * need to use the path, or the rename will fail if the temp file
  271.        * is not on the same drive as the output file.
  272.        */
  273.       sprintf(tmp_fname, "%s%s.tpn", opts.Output_Path, opts.Scene_Name);
  274.  
  275.       /* Move the old output file to a temporary file, so it can be
  276.        * read in and simultaneously written out to the new output file.
  277.        * Note that this can potentially be destructive, but it is
  278.        * impossible to change the output stream in mid-write.  We have
  279.        * to check if a temp file already exists, in case the transfer
  280.        * has been previously aborted.
  281.        */
  282.       if ((tmp_fp = fopen(tmp_fname,READ_FILE_STRING)) == NULL)
  283.       {
  284.         /* The temp file doesn't exist.  Try the original file. */
  285.         if ((tmp_fp = fopen(name,READ_FILE_STRING)) == NULL)
  286.         {
  287.           Status_Info("\n");
  288.           return(0);  /* Neither file exists - start from scratch. */
  289.         }
  290.         else /* The original file exists, but the temp file doesn't. */
  291.         {
  292.           fclose(tmp_fp);
  293.  
  294.           if (RENAME_FILE(name,tmp_fname) == RENAME_FILE_ERR)
  295.           {
  296.             Error("\nError making temporary PNG file for continuing trace.\n");
  297.           }
  298.  
  299.           /* Open the original file (now with a new name) for reading */
  300.           if ((tmp_fp = fopen(tmp_fname,READ_FILE_STRING)) == NULL)
  301.           {
  302.             RENAME_FILE(tmp_fname,name); /* Try to rename back - not crucial */
  303.             Error("\nError opening temporary PNG file for continuing trace.\n");
  304.           }
  305.         }
  306.       }
  307.       /* The temp file already exists.  If we can open the original file
  308.        * as well, then there is something wrong, and we can't automatically
  309.        * defide which file to delete.
  310.        */
  311.       else if((handle->file = fopen(name,READ_FILE_STRING)) != NULL)
  312.       {
  313.         fclose(tmp_fp);
  314.         fclose(handle->file);
  315.  
  316.         Error_Line("\nBoth original and temporary PNG files exist after an interrupted trace.\n");
  317.         Error("Please delete either %s or %s (preferrably the smaller).\n",name,tmp_fname);
  318.       }
  319.  
  320.       /* Try to open the new output file for writing.  If we can't, try
  321.        * to move the old one back so that users don't fret if it's missing.
  322.        * PNG will be able to continue without loss of data either way.
  323.        */
  324.       if ((handle->file = fopen(name, WRITE_FILE_STRING)) == NULL)
  325.       {
  326.         Status_Info("\n");
  327.  
  328.         fclose(tmp_fp);
  329.         RENAME_FILE(tmp_fname,name);
  330.         return(-1);
  331.       }
  332.  
  333.       if (buffer_size != 0)
  334.       {
  335.         handle->buffer = POV_MALLOC(buffer_size, "PNG file buffer");
  336.         setvbuf(handle->file, handle->buffer, _IOFBF, buffer_size);
  337.       }
  338.  
  339.       handle->buffer_size = buffer_size;
  340.  
  341.       /* The original input file */
  342.       if ((o_png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING,
  343.                        (png_voidp)FALSE, png_pov_err, png_pov_warn)) == NULL ||
  344.           (info_ptr = png_create_info_struct(o_png_ptr)) == NULL)
  345.       {
  346.         Error("Error allocating PNG data structures");
  347.       }
  348.  
  349.       if (setjmp(o_png_ptr->jmpbuf))
  350.       {
  351.         /* If we get here, we had a problem reading the file */
  352.         Status_Info("\n");
  353.  
  354.         if (handle->buffer != NULL)
  355.         {
  356.           POV_FREE(handle->buffer);
  357.           handle->buffer = NULL;
  358.         }
  359.  
  360.         png_destroy_read_struct(&o_png_ptr, &info_ptr, (png_infopp)NULL);
  361.  
  362.         fclose(handle->file);
  363.         handle->file = NULL;
  364.         fclose(tmp_fp);
  365.         tmp_fp = NULL;
  366.  
  367.         return(0);
  368.       }
  369.  
  370.       /* Set up the compression structure */
  371.       png_init_io(o_png_ptr, tmp_fp);
  372.  
  373.       /* Read in header info from the file */
  374.       png_read_info(o_png_ptr, info_ptr);
  375.  
  376.       if (info_ptr->color_type & ~(PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_ALPHA))
  377.       {
  378.         return(0);
  379.       }
  380.  
  381.       /* The new output file.  Thank god for re-entrant libpng/libgz code! */
  382.       if ((png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING,
  383.                      (png_voidp)TRUE, png_pov_err, png_pov_warn)) == NULL)
  384.       {
  385.         Error("Error allocating PNG data structures");
  386.       }
  387.  
  388.       if (setjmp(png_ptr->jmpbuf))
  389.       {
  390.         /* If we get here, we had a problem writing the file */
  391.         Status_Info("\n");
  392.  
  393.         if (handle->buffer != NULL)
  394.         {
  395.           POV_FREE(handle->buffer);
  396.           handle->buffer = NULL;
  397.         }
  398.  
  399.         png_destroy_read_struct(&o_png_ptr, &info_ptr, (png_infopp)NULL);
  400.         png_destroy_write_struct(&png_ptr, (png_infopp)NULL);
  401.  
  402.         fclose(handle->file);
  403.         handle->file = NULL;
  404.         fclose(tmp_fp);
  405.         tmp_fp = NULL;
  406.  
  407.         if (DELETE_FILE(name) != DELETE_FILE_ERR)
  408.         {
  409.           RENAME_FILE(tmp_fname,name);  /* Try to get the original file back */
  410.         }
  411.  
  412.         return(-1);
  413.       }
  414.  
  415.       /* Set up the compression structure */
  416.       png_init_io(png_ptr, handle->file);
  417.  
  418.       /* Fill in the relevant image information from the resumed file */
  419.       *width = handle->width = info_ptr->width;
  420.       *height = handle->height = info_ptr->height;
  421.  
  422.       /* Find out if file is a valid format, and if it had Alpha in it */
  423.       if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  424.       {
  425.         opts.Options |= OUTPUT_ALPHA;
  426.       }
  427.  
  428.       if ((info_ptr->color_type & PNG_COLOR_MASK_COLOR) == PNG_COLOR_TYPE_GRAY)
  429.       {
  430.         opts.Options |= HF_GRAY_16;
  431.         opts.PaletteOption = GREY;       /* Force grayscale preview */
  432.       }
  433.  
  434. #if defined(PNG_READ_sBIT_SUPPORTED)
  435.       if (info_ptr->valid & PNG_INFO_sBIT)
  436.       {
  437.         if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  438.         {
  439.           opts.OutputQuality = info_ptr->sig_bit.red;
  440.         }
  441.         else
  442.         {
  443.           opts.OutputQuality = info_ptr->sig_bit.gray;
  444.         }
  445.       }
  446.  
  447. #else /* !PNG_READ_sBIT_SUPPORTED */
  448.       if (info_ptr->bit_depth == 8 && opts.OutputQuality > 8 ||
  449.           info_ptr->bit_depth == 16 && opts.OutputQuality <= 8)
  450.       {
  451.         Error("\nSpecified color depth +fn%d not the same as depth %d in %s\n",
  452.               opts.OutputQuality, info_ptr->bit_depth, name);
  453.       }
  454. #endif /* !PNG_READ_sBIT_SUPPORTED */
  455.  
  456. #if defined(PNG_READ_oFFs_SUPPORTED)
  457.       opts.First_Column = info_ptr->x_offset;
  458.       opts.First_Line   = info_ptr->y_offset;
  459. #endif /* PNG_READ_oFFs_SUPPORTED */
  460.  
  461.       png_write_info(png_ptr, info_ptr);
  462.  
  463.       png_stride = info_ptr->color_type & PNG_COLOR_MASK_COLOR ? 3 : 1;
  464.  
  465.       if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  466.         png_stride++;
  467.  
  468.       png_stride *= (opts.OutputQuality + 7) / 8;
  469.  
  470.       row_ptr = (png_byte *)POV_MALLOC(*width*png_stride,"PNG read row buffer");
  471.       break;
  472.  
  473.     case WRITE_MODE:
  474.  
  475.       if (!strcmp(name,"-"))
  476.       {
  477.         buffer_size = 0;
  478.         handle->file = stdout;
  479.       }
  480.       else if ((handle->file = fopen(name, WRITE_FILE_STRING)) == NULL)
  481.       {
  482.         return(0);
  483.       }
  484.  
  485.       if (buffer_size != 0)
  486.       {
  487.         handle->buffer = POV_MALLOC((size_t)buffer_size, "PNG file buffer");
  488.  
  489.         setvbuf(handle->file, handle->buffer, _IOFBF, buffer_size);
  490.       }
  491.  
  492.       handle->buffer_size = buffer_size;
  493.  
  494.       if ((png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING,
  495.                      (png_voidp)TRUE, png_pov_err, png_pov_warn)) == NULL ||
  496.           (info_ptr = png_create_info_struct(png_ptr)) == NULL)
  497.       {
  498.         Error("Error allocating PNG data structures");
  499.       }
  500.  
  501.       if (setjmp(png_ptr->jmpbuf))
  502.       {
  503.         /* If we get here, we had a problem writing the file */
  504.         if (handle->buffer != NULL)
  505.         {
  506.           POV_FREE(handle->buffer);
  507.           handle->buffer = NULL;
  508.         }
  509.  
  510.         png_destroy_write_struct(&png_ptr, &info_ptr);
  511.  
  512.         fclose(handle->file);
  513.         handle->file = NULL;
  514.  
  515.         return(0);
  516.       }
  517.  
  518.       /* Set up the compression structure */
  519.  
  520.       png_init_io(png_ptr, handle->file);
  521.  
  522.       /* Fill in the relevant image information */
  523.  
  524.       info_ptr->width = handle->width = *width;
  525.       info_ptr->height = handle->height = *height;
  526.  
  527.       if (opts.OutputQuality > 16)
  528.       {
  529.         opts.OutputQuality = 16;
  530.       }
  531.       else if (opts.OutputQuality < 5)
  532.       {
  533.         opts.OutputQuality = 5;
  534.       }
  535.  
  536.       info_ptr->bit_depth = 8 * ((opts.OutputQuality + 7) / 8);
  537.  
  538.       if (opts.Options & HF_GRAY_16)
  539.       {
  540.         info_ptr->color_type = PNG_COLOR_TYPE_GRAY;
  541.       }
  542.       else
  543.       {
  544.         info_ptr->color_type = PNG_COLOR_TYPE_RGB;
  545.       }
  546.  
  547.       if (opts.Options & OUTPUT_ALPHA)
  548.       {
  549.         info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
  550.       }
  551.  
  552. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  553.       if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  554.       {
  555.         info_ptr->sig_bit.red =
  556.         info_ptr->sig_bit.green =
  557.         info_ptr->sig_bit.blue = opts.OutputQuality;
  558.       }
  559.       else
  560.       {
  561.         info_ptr->sig_bit.gray = opts.OutputQuality;
  562.       }
  563.  
  564.       if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  565.       {
  566.         info_ptr->sig_bit.alpha = opts.OutputQuality;
  567.       }
  568.  
  569.       info_ptr->valid |= PNG_INFO_sBIT;
  570. #endif /* PNG_WRITE_sBIT_SUPPORTED */
  571.  
  572. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  573.       if (handle->file_type & (IMAGE_FTYPE | GRAY_FTYPE))
  574.       {
  575.         info_ptr->gamma = 1.0/opts.DisplayGamma;
  576.         info_ptr->valid |= PNG_INFO_gAMA;
  577.       }
  578.       else if (handle->file_type & (HIST_FTYPE | HF_FTYPE))
  579.       {
  580.         info_ptr->gamma = 1.0;
  581.         info_ptr->valid |= PNG_INFO_gAMA;
  582.       }
  583. #endif /* PNG_WRITE_gAMA_SUPPORTED */
  584.  
  585. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  586.       if (opts.First_Column != 0 || opts.First_Line != 0)
  587.       {
  588.         info_ptr->x_offset = opts.First_Column;
  589.         info_ptr->y_offset = opts.First_Line;
  590.  
  591.         info_ptr->offset_unit_type = PNG_OFFSET_PIXEL;
  592.  
  593.         info_ptr->valid |= PNG_INFO_oFFs;
  594.       }
  595. #endif /* PNG_WRITE_oFFs_SUPPORTED */
  596.  
  597.       if (handle->file_type & HIST_FTYPE)
  598.       {
  599.       /* If we are writing a histogram file, we could potentially output
  600.        * a pCAL chunk with the max histogram value, to allow recovery of
  601.        * the original timing data.  However, pCAL is not yet official at
  602.        * the time of this writing.
  603.        */
  604.       }
  605.  
  606.       /* Use the maximum compression level - default is 6 */
  607.       png_set_compression_level(png_ptr, 9);
  608.  
  609.       png_write_info(png_ptr, info_ptr);
  610.  
  611.       png_stride = info_ptr->color_type & PNG_COLOR_MASK_COLOR ? 3 : 1;
  612.  
  613.       if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  614.         png_stride++;
  615.  
  616.       png_stride *= (opts.OutputQuality + 7) / 8;
  617.  
  618.       row_ptr = (png_byte *)POV_MALLOC(*width*png_stride, "PNG write row buffer");
  619.  
  620. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  621.       /* Set libpng to flush the output buffers every few lines, so that
  622.        * in case of a rude crash we don't lose very much data.
  623.        */
  624.       png_set_flush(png_ptr, FLUSH_DIST);
  625. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  626.  
  627.       break;
  628.  
  629.     case APPEND_MODE:
  630.  
  631. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  632.       if (setjmp(png_ptr->jmpbuf))
  633.       {
  634.         /* If we get here, we had a problem writing the file */
  635.  
  636.         if (handle->buffer != NULL)
  637.         {
  638.           POV_FREE(handle->buffer);
  639.           handle->buffer = NULL;
  640.         }
  641.  
  642.         png_destroy_write_struct(&png_ptr, &info_ptr);
  643.  
  644.         fclose(handle->file);
  645.         handle->file = NULL;
  646.  
  647.         return(0);
  648.       }
  649.  
  650.       /* Write out the data in the PNG/zlib buffers, and set automatic
  651.        * flushing for every few scanlines, in case of a rude crash.
  652.        */
  653.       png_write_flush(png_ptr);
  654.       png_set_flush(png_ptr, FLUSH_DIST);
  655. #else  /* !PNG_WRITE_FLUSH_SUPPORTED */
  656.       fflush(handle->file);
  657. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  658.  
  659.       if (strcmp(name,"-") && (handle->file =
  660.                      freopen(name, APPEND_FILE_STRING, handle->file)) == NULL)
  661.       {
  662.         if (handle->buffer != NULL)
  663.         {
  664.           POV_FREE(handle->buffer);
  665.           handle->buffer = NULL;
  666.         }
  667.  
  668.         png_destroy_write_struct(&png_ptr, &info_ptr);
  669.  
  670.         return(0);
  671.       }
  672.  
  673.       /* Delete the temporary data file.  Note that the new output file
  674.        * is all ready to go - nothing needs to be done here.
  675.        */
  676.       if (tmp_fp != NULL)
  677.       {
  678.         fclose(tmp_fp);
  679.         tmp_fp = NULL;
  680.  
  681.         if (DELETE_FILE(tmp_fname) == DELETE_FILE_ERR)
  682.         {
  683.           Warning(0.0,"Can't delete temporary PNG file %s.  Please delete it.\n",tmp_fname);
  684.         }
  685.       }
  686.   }
  687.  
  688.   return(1);
  689. }
  690.  
  691.  
  692.  
  693. /*****************************************************************************
  694. *
  695. * FUNCTION      : Write_Png_Line
  696. *
  697. * ARGUMENTS     : handle, line_data, line_number
  698. *
  699. * MODIFIED ARGS : none
  700. *
  701. * RETURN VALUE  : none
  702. *
  703. * AUTHOR        : Andreas Dilger
  704. *
  705. * DESCRIPTION
  706. *
  707. *   Write a line of data to the PNG file
  708. *
  709. * CHANGES
  710. *
  711. *   Updated for POV-Ray 3.X - [TIW]
  712. *   Updated to do flush output to reduce data loss - [AED]
  713. *   Updated to output Alpha channel if requested - [AED]
  714. *   Updated to output grayscale heightfield if requested - [AED]
  715. *   Updated to allow grayscale in 5-8 bpp if desired, Oct 1995 - [AED]
  716. *   Updated to allow grayscale and alpha together, Oct 1995 - [AED]
  717. *   Changed how bit-depths 9-15 get promoted to 16 bits based on new
  718. *     recommendations from the PNG Group,  Nov 1995 - [AED]
  719. *
  720. ******************************************************************************/
  721.  
  722. static void Write_Png_Line(handle, line_data, line_number)
  723. FILE_HANDLE *handle;
  724. COLOUR *line_data;
  725. int line_number;
  726. {
  727.   register int col, j;
  728.   int himask;
  729.   int color;
  730.  
  731.  
  732.   /*
  733.    * We must copy all the values because PNG expects RGBRGB bytes, but
  734.    * POV-Ray stores RGB components in separate arrays as floats.  In
  735.    * order to use the full scale values at the lower bit depth, PNG
  736.    * recommends filling the low-order bits with a copy of the high-order
  737.    * bits.  However, studies have shown that filling the low order bits
  738.    * with constant bits significantly improves compression, which I'm
  739.    * doing here.  Note that since the true bit depth is stored in the
  740.    * sBIT chunk, the extra packed bits are not important.
  741.    */
  742.  
  743.   switch (opts.OutputQuality)
  744.   {
  745.     case 5:
  746.     case 6:
  747.     case 7:
  748.       /* Handle shifting for arbitrary output bit depth */
  749.  
  750.       himask = 0xFF ^ ((1 << (8 - opts.OutputQuality)) - 1);
  751.  
  752.       if ((info_ptr->color_type & PNG_COLOR_MASK_COLOR) == PNG_COLOR_TYPE_GRAY)
  753.       {
  754.         for (col = j = 0; col < handle->width; col++, j += png_stride)
  755.         {
  756.           color = (png_byte)floor((line_data[col][RED]*0.30 +
  757.                                    line_data[col][GREEN]*0.59 +
  758.                                    line_data[col][BLUE]*0.11) * 255.0);
  759.  
  760.           /* Use left-bit replication (LBR) for bit depths < 8 */
  761.           row_ptr[j] = color & himask;
  762.           row_ptr[j] |= color >> opts.OutputQuality;
  763.  
  764.           /* Handle Alpha here if needed - must use exact bit replication
  765.            * instead of truncation or 100... termination
  766.            */
  767.           if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  768.           {
  769.             color = 255 - (int)floor(line_data[col][TRANSM] * 255.0);
  770.  
  771.             row_ptr[j + 1] = color & himask;
  772.             row_ptr[j + 1] |= color >> opts.OutputQuality;
  773.           }
  774.         }
  775.       }
  776.       else
  777.       {
  778.         for (col = j = 0; col < handle->width; col++, j += png_stride)
  779.         {
  780.           color = (int)floor(line_data[col][RED]   * 255.0);
  781.  
  782.           row_ptr[j] = color & himask;
  783.           row_ptr[j] |= color >> opts.OutputQuality;
  784.  
  785.           color = (int)floor(line_data[col][GREEN] * 255.0);
  786.  
  787.           row_ptr[j + 1] = color & himask;
  788.           row_ptr[j + 1] |= color >> opts.OutputQuality;
  789.  
  790.           color = (int)floor(line_data[col][BLUE]  * 255.0);
  791.  
  792.           row_ptr[j + 2] = color & himask;
  793.           row_ptr[j + 2] |= color >> opts.OutputQuality;
  794.  
  795.           /* Handle Alpha here if needed */
  796.           if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  797.           {
  798.             color = 255 - (int)floor(line_data[col][TRANSM] * 255.0);
  799.  
  800.             row_ptr[j + 3] = color & himask;
  801.             row_ptr[j + 3] |= color >> opts.OutputQuality;
  802.           }
  803.         }
  804.       }
  805.       break;
  806.  
  807.     case 8:
  808.       if ((info_ptr->color_type & PNG_COLOR_MASK_COLOR) == PNG_COLOR_TYPE_GRAY)
  809.       {
  810.         for (col = j = 0; col < handle->width; col++, j += png_stride)
  811.         {
  812.           row_ptr[j] = (png_byte)floor((line_data[col][RED]*0.30 +
  813.                                         line_data[col][GREEN]*0.59 +
  814.                                         line_data[col][BLUE]*0.11) * 255.0);
  815.  
  816.           /* Handle Alpha here if needed */
  817.           if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  818.           {
  819.             row_ptr[j+1] = (png_byte)(255-floor(line_data[col][TRANSM]*255.0));
  820.           }
  821.         }
  822.       }
  823.       else
  824.       {
  825.         for (col = j = 0; col < handle->width; col++, j += png_stride)
  826.         {
  827.           row_ptr[j] = (png_byte)floor(line_data[col][RED]   * 255.0);
  828.           row_ptr[j + 1] = (png_byte)floor(line_data[col][GREEN] * 255.0);
  829.           row_ptr[j + 2] = (png_byte)floor(line_data[col][BLUE]  * 255.0);
  830.  
  831.           /* Handle Alpha here if needed */
  832.           if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  833.           {
  834.             row_ptr[j+3] = (png_byte)(255-floor(line_data[col][TRANSM]*255.0));
  835.           }
  836.         }
  837.       }
  838.       break;
  839.  
  840.     case 16:
  841.       if ((info_ptr->color_type & PNG_COLOR_MASK_COLOR) == PNG_COLOR_TYPE_GRAY)
  842.       {
  843.         for (col = j = 0; col < handle->width; col++, j += png_stride)
  844.         {
  845.           color = (int)floor((line_data[col][RED]*0.30 +
  846.                               line_data[col][GREEN]*0.59 +
  847.                               line_data[col][BLUE]*0.11) * 65535.0);
  848.  
  849.           row_ptr[j] = color >> 8;
  850.           row_ptr[j + 1] = color & 0xFF;
  851.  
  852.           /* Handle Alpha here if needed */
  853.           if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  854.           {
  855.             color = 65535 - (int)floor(line_data[col][TRANSM]  * 65535.0);
  856.  
  857.             row_ptr[j + 2] = color >> 8;
  858.             row_ptr[j + 3] = color & 0xFF;
  859.           }
  860.         }
  861.       }
  862.       else
  863.       {
  864.         for (col = j = 0; col < handle->width; col++, j += png_stride)
  865.         {
  866.           color = (int)floor(line_data[col][RED]   * 65535.0);
  867.  
  868.           row_ptr[j] = color >> 8;
  869.           row_ptr[j + 1] = color & 0xFF;
  870.  
  871.           color = (int)floor(line_data[col][GREEN] * 65535.0);
  872.  
  873.           row_ptr[j + 2] = color >> 8;
  874.           row_ptr[j + 3] = color & 0xFF;
  875.  
  876.           color = (int)floor(line_data[col][BLUE]  * 65535.0);
  877.  
  878.           row_ptr[j + 4] = color >> 8;
  879.           row_ptr[j + 5] = color & 0xFF;
  880.  
  881.           /* Handle Alpha here if needed */
  882.           if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  883.           {
  884.             color = 65535 - (int)floor(line_data[col][TRANSM]  * 65535.0);
  885.  
  886.             row_ptr[j + 6] = color >> 8;
  887.             row_ptr[j + 7] = color & 0xFF;
  888.           }
  889.         }
  890.       }
  891.       break;
  892.  
  893.     default:  /* OutputQuality 9 - 15 */
  894.       /* Handle shifting for arbitrary output bit depth */
  895.       himask = 0xFF ^ ((1 << (16 - opts.OutputQuality)) - 1);
  896.  
  897.       if ((info_ptr->color_type & PNG_COLOR_MASK_COLOR) == PNG_COLOR_TYPE_GRAY)
  898.       {
  899.         for (col = j = 0; col < handle->width; col++, j += png_stride)
  900.         {
  901.           color = (int)floor((line_data[col][RED]*0.30 +
  902.                               line_data[col][GREEN]*0.59 +
  903.                               line_data[col][BLUE]*0.11) * 65535.0);
  904.  
  905.           row_ptr[j] = color >> 8;
  906.           row_ptr[j + 1] = color & himask;
  907.  
  908.           if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  909.           {
  910.             color = 65535 - (int)floor(line_data[col][TRANSM] * 65535.0);
  911.  
  912.             row_ptr[j + 2] = color >> 8;
  913.             row_ptr[j + 3] = color & himask;
  914.             row_ptr[j + 3] |= color >> opts.OutputQuality;
  915.           }
  916.         }
  917.       }
  918.       else
  919.       {
  920.         for (col = j = 0; col < handle->width; col++, j += png_stride)
  921.         {
  922.           color = (int)floor(line_data[col][RED]   * 65535.0);
  923.  
  924.           row_ptr[j] = color >> 8;
  925.           row_ptr[j + 1] = color & himask;
  926.  
  927.           color = (int)floor(line_data[col][GREEN] * 65535.0);
  928.  
  929.           row_ptr[j + 2] = color >> 8;
  930.           row_ptr[j + 3] = color & himask;
  931.  
  932.           color = (int)floor(line_data[col][BLUE]  * 65535.0);
  933.  
  934.           row_ptr[j + 4] = color >> 8;
  935.           row_ptr[j + 5] = color & himask;
  936.  
  937.           /* Handle Alpha here if needed */
  938.           if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  939.           {
  940.             color = 65535 - (int)floor(line_data[col][TRANSM]  * 65535.0);
  941.  
  942.             row_ptr[j + 6] = color >> 8;
  943.             row_ptr[j + 7] = color & himask;
  944.             row_ptr[j + 7] |= color >> opts.OutputQuality;
  945.           }
  946.         }
  947.       }
  948.   }
  949.  
  950.   if (setjmp(png_ptr->jmpbuf))
  951.   {
  952.     /* If we get here, we had a problem writing the file */
  953.     fclose(handle->file);
  954.     handle->file = NULL;
  955.  
  956.     Error("Error writing PNG output data to %s.\n", handle->file);
  957.   }
  958.  
  959.   /* Write out a scanline */
  960.   png_write_row(png_ptr, row_ptr);
  961.  
  962.   /* Close and reopen file (if not stdout) for integrity in case we crash */
  963.   if (handle->buffer_size == 0 && strcmp(handle->filename, "-"))
  964.   {
  965. #ifndef PNG_WRITE_FLUSH
  966.     fflush(handle->file);
  967. #endif
  968.  
  969.     handle->file = freopen(handle->filename, APPEND_FILE_STRING, handle->file);
  970.   }
  971. }
  972.  
  973.  
  974.  
  975. /*****************************************************************************
  976. *
  977. * FUNCTION      : Read_Png_Line
  978. *
  979. * ARGUMENTS     : FILE_HANDLE *handle; COLOUR *line_data; int *line_number;
  980. *
  981. * MODIFIED ARGS : none
  982. *
  983. * RETURN VALUE  : 1 if no error exit
  984. *
  985. * AUTHOR        : Andreas Dilger
  986. *
  987. * DESCRIPTION
  988. *
  989. *   Read a line of PNG data
  990. *
  991. * CHANGES
  992. *
  993. *   Updated for POV-Ray 3.X - [TIW]
  994. *   Updated to handle interrupted file resuming Sept 1995 - [AED]
  995. *   Updated to support grayscale and alpha together, Oct 1995 - [AED]
  996. *
  997. ******************************************************************************/
  998.  
  999. static int Read_Png_Line(handle, line_data, line_number)
  1000. FILE_HANDLE *handle;
  1001. COLOUR *line_data;
  1002. int *line_number;
  1003. {
  1004.   register int col, j, step;
  1005.  
  1006.   if (setjmp(o_png_ptr->jmpbuf))
  1007.   {
  1008.     /* If we get here, we had a problem reading the file, which probably
  1009.      * means that we have read all the available data, rather than a real
  1010.      * error, but there is no sure way to know.
  1011.      */
  1012.     Status_Info("\n");
  1013.     return(0);
  1014.   }
  1015.  
  1016.   if (setjmp(png_ptr->jmpbuf))
  1017.   {
  1018.     /* If we get here, we had a problem writing the new file */
  1019.     Status_Info("\n");
  1020.  
  1021.     fclose(handle->file);
  1022.     handle->file = NULL;
  1023.     fclose(tmp_fp);
  1024.     tmp_fp = NULL;
  1025.  
  1026.     if (DELETE_FILE(handle->filename) != DELETE_FILE_ERR)
  1027.     {
  1028.       RENAME_FILE(tmp_fname,handle->filename); /* Move original file back */
  1029.     }
  1030.  
  1031.     return(-1);
  1032.   }
  1033.  
  1034.   /* Read in another row if available */
  1035.   png_read_row(o_png_ptr, row_ptr, NULL);
  1036.  
  1037.   /* We won't get here if there was a read error */
  1038.   png_write_row(png_ptr, row_ptr);
  1039.  
  1040.   if (*line_number % 32 == 31)
  1041.     Status_Info(".");
  1042.   
  1043.   /*
  1044.    * We must copy all the values because PNG supplies RGBRGB, but POV-Ray
  1045.    * stores RGB components in separate arrays.  Note that since we have
  1046.    * already written the data out to the temporary file, we only need to
  1047.    * use the top 8 bits for the line_data info as it is only used for
  1048.    * potential screen output.
  1049.    */
  1050.  
  1051.   /* How many bytes in a sample */
  1052.   step = (info_ptr->bit_depth <= 8) ? 1 : 2;
  1053.  
  1054.   if ((info_ptr->color_type & PNG_COLOR_MASK_COLOR) == PNG_COLOR_TYPE_GRAY)
  1055.   {
  1056.     for (col = j = 0; col < handle->width; col++, j += png_stride)
  1057.     {
  1058.       line_data[col][RED] = (DBL)row_ptr[j] / 255.0;
  1059.       line_data[col][GREEN] = (DBL)row_ptr[j] / 255.0;
  1060.       line_data[col][BLUE] = (DBL)row_ptr[j] / 255.0;
  1061.  
  1062.       if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  1063.       {
  1064.         line_data[col][TRANSM] = (DBL)(255 - row_ptr[j + step]) / 255.0;
  1065.       }
  1066.     }
  1067.   }
  1068.   else
  1069.   {
  1070.     for (col = j = 0; col < handle->width; col++, j += png_stride)
  1071.     {
  1072.       line_data[col][RED] = (DBL)row_ptr[j] / 255.0;
  1073.       line_data[col][GREEN] = (DBL)row_ptr[j + step] / 255.0;
  1074.       line_data[col][BLUE] = (DBL)row_ptr[j + 2*step] / 255.0;
  1075.  
  1076.       if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  1077.       {
  1078.         line_data[col][TRANSM] = (DBL)(255 - row_ptr[j + 3*step]) / 255.0;
  1079.       }
  1080.     }
  1081.   }
  1082.  
  1083.   /* Note that line_number is the line number of the completed row, not
  1084.    * the next row!
  1085.    */
  1086. #if defined(PNG_READ_oFFS_SUPPORTED)
  1087.   *line_number = info_ptr->y_offset + png_ptr->row_number - 1;
  1088. #else
  1089.   *line_number = png_ptr->row_number - 1;
  1090. #endif
  1091.  
  1092.   return(1);
  1093. }
  1094.  
  1095.  
  1096.  
  1097. /*****************************************************************************
  1098. *
  1099. * FUNCTION      : Close_Png_File
  1100. *
  1101. * ARGUMENTS     : FILE_HANDLE *handle
  1102. *
  1103. * MODIFIED ARGS : handle
  1104. *
  1105. * RETURN VALUE  : none
  1106. *
  1107. * AUTHOR        : Andreas Dilger
  1108. *
  1109. * DESCRIPTION
  1110. *
  1111. *   Write any chunks coming after image (eg comments), and free all the
  1112. *   memory associated with the PNG IO streams.  Will output some rendering
  1113. *   stats and info into tEXt chunks if POV_COMMENTS is #defined, and will
  1114. *   also record the rendering time if CTIME is #defined.
  1115. *
  1116. * CHANGES
  1117. *
  1118. *   Updated for POV-Ray 3.X - [TIW]
  1119. *
  1120. ******************************************************************************/
  1121.  
  1122. static void Close_Png_File(handle)
  1123. FILE_HANDLE *handle;
  1124. {
  1125. #ifdef POV_COMMENTS
  1126.   int n, index = - 1;
  1127.   png_text *text_ptr = NULL;
  1128.   char allocated[NTEXT];        /* Boolean array if text is MALLOCed */
  1129.   char bigtext[MAXTEXT];        /* Large temporary string to print into */
  1130. # ifdef CAMERA
  1131.   CAMERA *Camera = Frame.Camera;
  1132. # endif
  1133. #ifdef CTIME
  1134.   char months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
  1135.                    "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
  1136. #endif
  1137. #endif
  1138.  
  1139.   /* Why are we here? */
  1140.  
  1141.   if (handle->file == NULL)
  1142.   {
  1143.     return;
  1144.   }
  1145.  
  1146.   if (handle->mode == WRITE_MODE || handle->mode == APPEND_MODE)
  1147.   {
  1148.     if (png_ptr != NULL)
  1149.     {
  1150.       if (setjmp(png_ptr->jmpbuf))
  1151.       {
  1152.         /* If we get here, we had a problem writing the file */
  1153.  
  1154.         png_destroy_write_struct(&png_ptr, &info_ptr);
  1155.  
  1156.         if (row_ptr != NULL)
  1157.         {
  1158.           POV_FREE(row_ptr);
  1159.           row_ptr = NULL;
  1160.         }
  1161.  
  1162.         if (handle->file != NULL)
  1163.         {
  1164.           fclose (handle->file);
  1165.           handle->file = NULL;
  1166.         }
  1167.  
  1168.         if (handle->buffer != NULL)
  1169.         {
  1170.           POV_FREE(handle->buffer);
  1171.           handle->buffer = NULL;
  1172.         }
  1173.  
  1174.         Error("Error writing PNG file.");
  1175.       }
  1176.  
  1177.       if(png_ptr->row_number < png_ptr->num_rows)
  1178.       {
  1179.          /* finished prematurely - trick into thinking done*/
  1180.          png_ptr->num_rows = png_ptr->row_number;
  1181.          png_write_finish_row(png_ptr);
  1182.       }
  1183.  
  1184. #ifdef POV_COMMENTS /* temporarily skip comment writing code */
  1185.       if (info_ptr != NULL)
  1186.       {
  1187. #if defined(PNG_WRITE_tIME_SUPPORTED)
  1188.         png_convert_from_time_t(&info_ptr->mod_time, tstart);
  1189.         info_ptr->valid = PNG_INFO_tIME;
  1190. #endif /* PNG_WRITE_tIME_SUPPORTED */
  1191.  
  1192. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  1193.         text_ptr = (png_text *)POV_MALLOC(NTEXT*sizeof(png_text), "PNG comment structure");
  1194.  
  1195.         /* Init allocation flags. */
  1196.         for (n = 0; n < NTEXT; n++)
  1197.         {
  1198.           allocated[n] = FALSE;
  1199.           text_ptr[n].compression = - 1;
  1200.         }
  1201.  
  1202. #ifdef TRACER
  1203.         text_ptr[++index].key = "Author";
  1204.         text_ptr[index].text = TRACER;
  1205.         text_ptr[index].text_length = strlen(text_ptr[index].text);
  1206. #endif
  1207.  
  1208. #ifdef COPYRIGHT
  1209.         text_ptr[++index].key = "Copyright";
  1210.         /* 0xA9 is the ISO-8859-1 (used in PNG tEXt) copyright character */
  1211.         sprintf(bigtext, "Copyright %c %d %s", 0xA9, info_ptr->mod_time.year,
  1212.                                                COPYRIGHT);
  1213.         text_ptr[index].text_length = strlen(bigtext);
  1214.         text_ptr[index].text = (char *)POV_MALLOC(text_ptr[index].text_length + 1, "PNG comment");
  1215.         strcpy(text_ptr[index].text, bigtext);
  1216.         allocated[index] = TRUE;
  1217.         if (text_ptr[index].text_length > 200) /* Compress if long copyright */
  1218.           text_ptr[index].compression = 0;
  1219. #endif
  1220.  
  1221. #ifdef CTIME
  1222.         /* Print the image "creation" time in RFC 1123 format */
  1223.         text_ptr[++index].key = "Creation Time";
  1224.         sprintf(bigtext, "%02d %3s %4d %02d:%02d:%02d GMT",
  1225.                 info_ptr->mod_time.day, months[info_ptr->mod_time.month],
  1226.                 info_ptr->mod_time.year, info_ptr->mod_time.hour, 
  1227.                 info_ptr->mod_time.minute, info_ptr->mod_time.second);
  1228.         text_ptr[index].text_length = strlen(bigtext);
  1229.         text_ptr[index].text = (char *)POV_MALLOC(text_ptr[index].text_length + 1, "PNG comment");
  1230.         strcpy(text_ptr[index].text, bigtext);
  1231.         allocated[index] = TRUE;
  1232. #endif
  1233.  
  1234.         text_ptr[++index].key = "Source";
  1235.         sprintf(bigtext, "Persistence of Vision(tm) Ray Tracer v%s%s",
  1236.                 POV_RAY_VERSION, COMPILER_VER);
  1237.         text_ptr[index].text_length = strlen(bigtext);
  1238.         text_ptr[index].text = (char *)POV_MALLOC(text_ptr[index].text_length + 1, "PNG comment");
  1239.         strcpy(text_ptr[index].text, bigtext);
  1240.         allocated[index] = TRUE;
  1241.  
  1242.         if (strcmp(opts.Input_File_Name, "-"))
  1243.         {
  1244.           text_ptr[++index].key = "Input File";
  1245.           text_ptr[index].text = opts.Input_File_Name;
  1246.           text_ptr[index].text_length = strlen(text_ptr[index].text);
  1247.         }
  1248.  
  1249. #ifdef CAMERA
  1250.         text_ptr[++index].key = "POV Camera";
  1251.         sprintf(bigtext, "Location:   %7g %7g %7g\n"
  1252.           "           Direction:  %7g %7g %7g\n"
  1253.           "           Up:         %7g %7g %7g\n"
  1254.           "           Right:      %7g %7g %7g\n"
  1255.           "           Sky:        %7g %7g %7g",
  1256.           Camera->Location[X], Camera->Location[Y], Camera->Location[Z],
  1257.           Camera->Direction[X], Camera->Direction[Y], Camera->Direction[Z],
  1258.           Camera->Up[X], Camera->Up[Y], Camera->Up[Z],
  1259.           Camera->Right[X], Camera->Right[Y], Camera->Right[Z],
  1260.           Camera->Sky[X], Camera->Sky[Y], Camera->Sky[Z]);
  1261.         text_ptr[index].text_length = strlen(bigtext);
  1262.         text_ptr[index].text = (char *)POV_MALLOC(text_ptr[index].text_length + 1, "PNG comment");
  1263.         strcpy(text_ptr[index].text, bigtext);
  1264.         allocated[index] = TRUE;
  1265. #endif
  1266.  
  1267.         if (opts.FrameSeq.Clock_Value != 0)
  1268.         {
  1269.           text_ptr[++index].key = "POV Clock";
  1270.           sprintf(bigtext, "%g", opts.FrameSeq.Clock_Value);
  1271.           text_ptr[index].text_length = strlen(bigtext);
  1272.           text_ptr[index].text = (char *)POV_MALLOC(text_ptr[index].text_length + 1, "PNG comment");
  1273.           strcpy(text_ptr[index].text, bigtext);
  1274.           allocated[index] = TRUE;
  1275.         }
  1276.  
  1277.         if (opts.Quality != 9)
  1278.         {
  1279.           text_ptr[++index].key = "Rendering Quality";
  1280.           sprintf(bigtext, "%d", opts.Quality);
  1281.           text_ptr[index].text_length = strlen(bigtext);
  1282.           text_ptr[index].text = (char *)POV_MALLOC(text_ptr[index].text_length + 1, "PNG comment");
  1283.           strcpy(text_ptr[index].text, bigtext);
  1284.           allocated[index] = TRUE;
  1285.         }
  1286.  
  1287.         text_ptr[++index].key = "Rendering Time";
  1288.         sprintf(bigtext, "%g s", trender);
  1289.         text_ptr[index].text_length = strlen(bigtext);
  1290.         text_ptr[index].text = (char *)POV_MALLOC(text_ptr[index].text_length + 1, "PNG comment");
  1291.         strcpy(text_ptr[index].text, bigtext);
  1292.         allocated[index] = TRUE;
  1293.  
  1294.         info_ptr->num_text = index + 1;
  1295.         info_ptr->max_text = NTEXT;
  1296.         info_ptr->text = text_ptr;
  1297. #endif  /* PNG_WRITE_tEXt_SUPPORTED */
  1298.       }
  1299. #endif  /* POV_COMMENTS */ 
  1300.  
  1301.       png_write_end(png_ptr, info_ptr);
  1302.       png_destroy_write_struct(&png_ptr, &info_ptr);
  1303.  
  1304. #ifdef POV_COMMENTS
  1305.       if (text_ptr != NULL)
  1306.       {
  1307.         for (n = 0; n <= index; n++)
  1308.         {
  1309.           if (allocated[n])
  1310.           {
  1311.             POV_FREE(text_ptr[n].text);
  1312.           }
  1313.         }
  1314.  
  1315.         POV_FREE(text_ptr);
  1316.         text_ptr = NULL;
  1317.       }
  1318. #endif /* POV_COMMENTS */
  1319.  
  1320.     }
  1321.  
  1322.     if (row_ptr != NULL)
  1323.     {
  1324.       POV_FREE(row_ptr);
  1325.       row_ptr = NULL;
  1326.     }
  1327.  
  1328.     if (handle->file != NULL)
  1329.     {
  1330.       fclose (handle->file);
  1331.       handle->file = NULL;
  1332.     }
  1333.  
  1334.     if (handle->buffer != NULL)
  1335.     {
  1336.       POV_FREE(handle->buffer);
  1337.       handle->buffer = NULL;
  1338.     }
  1339.   }
  1340.   else /* READ_MODE */
  1341.   {
  1342.     if (o_png_ptr != NULL)
  1343.     {
  1344.       png_destroy_read_struct(&o_png_ptr, (png_infopp)NULL, (png_infopp)NULL);
  1345.     }
  1346.   }
  1347. }
  1348.  
  1349.  
  1350. /*****************************************************************************
  1351. *
  1352. * FUNCTION      : Read_Png_Image
  1353. *
  1354. * ARGUMENTS     : IMAGE *Image; char *name;
  1355. *
  1356. * MODIFIED ARGS : Image
  1357. *
  1358. * RETURN VALUE  : none
  1359. *
  1360. * AUTHOR        : Andreas Dilger
  1361. *
  1362. * DESCRIPTION
  1363. *
  1364. *   Reads a PNG image into an RGB image buffer
  1365. *
  1366. * CHANGES
  1367. *
  1368. *   Updated for POV-Ray 3.X - [TIW]
  1369. *   Updated to allow grayscale and alpha together, Oct 1995 - [AED]
  1370. *   Fixed palette size for grayscale images with bit-depth <= 8, Nov 1995 [AED]
  1371. *   Changed how grayscale images > 8bpp are stored based on use, Nov 1995 [AED]
  1372. *
  1373. ******************************************************************************/
  1374.  
  1375. void Read_Png_Image(Image, name)
  1376. IMAGE *Image;
  1377. char *name;
  1378. {
  1379.   unsigned int width, height;
  1380.   int row, col, j;
  1381.   int stride;
  1382.   FILE *filep;
  1383.   IMAGE_LINE *line_data;
  1384.   png_struct *r_png_ptr;
  1385.   png_info *r_info_ptr;
  1386.   png_byte **row_ptrs;
  1387.  
  1388.   /* Start by trying to open the file */
  1389.  
  1390.   if ((filep = Locate_File(name, READ_FILE_STRING, ".png", ".PNG",TRUE)) == NULL)
  1391.   {
  1392.     Error("Error opening PNG file.\n");
  1393.   }
  1394.  
  1395.   if ((r_png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING,
  1396.                    (png_voidp)TRUE, png_pov_err, png_pov_warn)) == NULL ||
  1397.       (r_info_ptr = png_create_info_struct(png_ptr)) == NULL)
  1398.   {
  1399.     Error("Error allocating PNG data structures");
  1400.   }
  1401.  
  1402.   if (setjmp(r_png_ptr->jmpbuf))
  1403.   {
  1404.     /* If we get here, we had a problem reading the file */
  1405.  
  1406.     png_destroy_read_struct(&r_png_ptr, &r_info_ptr, (png_infopp)NULL);
  1407.     Error("Error reading PNG image.");
  1408.   }
  1409.  
  1410.   /* set up the input control */
  1411.  
  1412.   png_init_io(r_png_ptr, filep);
  1413.  
  1414.   /* read the file information */
  1415.  
  1416.   png_read_info(r_png_ptr, r_info_ptr);
  1417.  
  1418.   width = r_info_ptr->width;
  1419.   height = r_info_ptr->height;
  1420.  
  1421.   Image->iwidth = width;
  1422.   Image->iheight = height;
  1423.   Image->width = (DBL)width;
  1424.   Image->height = (DBL)height;
  1425.  
  1426.   /* Allocate buffers for the image */
  1427.   stride = 1;
  1428.  
  1429.   if (r_info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  1430.   {
  1431.     IMAGE_COLOUR *cmap;
  1432.     png_color *png_cmap;
  1433.     int cmap_len = r_info_ptr->num_palette;
  1434.     int index;
  1435.  
  1436.     Image->Colour_Map_Size = cmap_len;
  1437.  
  1438.     cmap = (IMAGE_COLOUR *)POV_MALLOC(cmap_len*sizeof(IMAGE_COLOUR), "PNG image color map");
  1439.  
  1440.     Image->Colour_Map = cmap;
  1441.     png_cmap = r_info_ptr->palette;
  1442.  
  1443.     for (index = 0; index < cmap_len; index++)
  1444.     {
  1445.       cmap[index].Red = png_cmap[index].red;
  1446.       cmap[index].Green = png_cmap[index].green;
  1447.       cmap[index].Blue = png_cmap[index].blue;
  1448.       cmap[index].Filter = 0;
  1449.       cmap[index].Transmit = 0;
  1450.     }
  1451.  
  1452.     if (r_info_ptr->valid & PNG_INFO_tRNS)
  1453.     {
  1454.       for (index = 0; index < r_info_ptr->num_trans; index++)
  1455.         cmap[index].Transmit = 255 - r_info_ptr->trans[index];
  1456.     }
  1457.  
  1458.     Image->data.map_lines = (unsigned char **)
  1459.       POV_MALLOC(height * sizeof(unsigned char *), "PNG image");
  1460.  
  1461.     /* tell pnglib to expand data to 1 pixel/byte */
  1462.     png_set_packing(r_png_ptr);
  1463.   }
  1464.   else if (r_info_ptr->color_type == PNG_COLOR_TYPE_GRAY &&
  1465.            r_info_ptr->bit_depth <= 8)
  1466.   {
  1467.     IMAGE_COLOUR *cmap;
  1468.     int cmap_len;
  1469.     int index;
  1470.     
  1471.     Image->Colour_Map_Size = cmap_len = 1 << r_info_ptr->bit_depth;
  1472.     
  1473.     cmap = (IMAGE_COLOUR *)POV_MALLOC(cmap_len*sizeof(IMAGE_COLOUR), "PNG image color map");
  1474.  
  1475.     Image->Colour_Map = cmap;
  1476.  
  1477.     for (index = 0; index < cmap_len; index++)
  1478.     {
  1479.       cmap[index].Red =
  1480.       cmap[index].Green =
  1481.       cmap[index].Blue = index;
  1482.       cmap[index].Filter = 0;
  1483.       cmap[index].Transmit = 0;
  1484.     }
  1485.  
  1486.     if (r_info_ptr->valid & PNG_INFO_tRNS)
  1487.     {
  1488.       for (index = 0; index < r_info_ptr->num_trans; index++)
  1489.         cmap[index].Transmit = 255 - r_info_ptr->trans[index];
  1490.     }
  1491.  
  1492.     Image->data.map_lines = (unsigned char **)
  1493.       POV_MALLOC(height * sizeof(unsigned char *), "PNG image");
  1494.     
  1495.     /* tell pnglib to expand data to 1 pixel/byte */
  1496.     png_set_packing(r_png_ptr);
  1497.   }
  1498.   else if (r_info_ptr->color_type == PNG_COLOR_TYPE_GRAY ||
  1499.            r_info_ptr->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  1500.   {
  1501.     Image->Colour_Map = NULL;
  1502.     
  1503.     Image->data.rgb_lines = (IMAGE_LINE *)
  1504.       POV_MALLOC(height * sizeof(IMAGE_LINE), "PNG image");
  1505.  
  1506.     if (r_info_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  1507.     {
  1508.       stride = 2;
  1509.     }
  1510.     else if (r_info_ptr->bit_depth <= 8) /* PNG_COLOR_TYPE_GRAY_ALPHA */
  1511.     {
  1512.       /* tell pnglib to expand data to 1 pixel/byte */
  1513.       png_set_packing(r_png_ptr);
  1514.       stride = 2;
  1515.     }
  1516.     else                                  /* PNG_COLOR_TYPE_GRAY_ALPHA */
  1517.     {
  1518.       stride = 4;
  1519.     }
  1520.   }
  1521.   else if (r_info_ptr->color_type == PNG_COLOR_TYPE_RGB ||
  1522.       r_info_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  1523.   {
  1524.     Image->Colour_Map = NULL;
  1525.     
  1526.     /* tell pnglib to strip 16 bit depth files down to 8 bits */
  1527.     if (r_info_ptr->bit_depth > 8)
  1528.     {
  1529.       if (opts.Options & VERBOSE)
  1530.         Warning(0.0,"\nConverting PNG image map to 8 bits/sample from higher bit depth.");
  1531.       png_set_strip_16(r_png_ptr);
  1532.     }
  1533.     
  1534.     Image->data.rgb_lines = (IMAGE_LINE *)
  1535.     POV_MALLOC(height * sizeof(IMAGE_LINE), "PNG image");
  1536.  
  1537.     if (r_info_ptr->color_type == PNG_COLOR_TYPE_RGB)
  1538.       stride = 3;
  1539.     else                               /* PNG_COLOR_TYPE_RGB_ALPHA */
  1540.       stride = 4;
  1541.   }
  1542.   else                                 /* Unknown PNG type */
  1543.   {
  1544.     Error("Unsupported color type %d in PNG image.\n", r_info_ptr->color_type);
  1545.   }
  1546.   
  1547.   /* Tell pnglib to handle the gamma conversion for you.  Note that
  1548.    * GammaFactor * DisplayFactor = assumed_gamma, so we are converting
  1549.    * images into the "internal gamma" space of POV (rather than to a
  1550.    * gamma of 1.0) to avoid doing gamma correction on image maps twice for
  1551.    * those scene files which don't have a gamma of 1.0.  For POV 3.0,
  1552.    * we will only do input gamma conversion on those files which will be
  1553.    * used as image maps, and the other types will load the raw pixel values.
  1554.    */
  1555. #if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_READ_gAMA_SUPPORTED)
  1556.   if (r_info_ptr->valid & PNG_INFO_gAMA && (Image->Image_Type & IMAGE_FTYPE))
  1557.   {
  1558.     png_set_gamma(r_png_ptr, opts.GammaFactor*opts.DisplayGamma,
  1559.                                                           r_info_ptr->gamma);
  1560.   }
  1561. #endif /* PNG_READ_GAMMA_SUPPORTED and PNG_READ_gAMA_SUPPORTED */
  1562.     
  1563.   png_set_interlace_handling(png_ptr);
  1564.   png_read_update_info(png_ptr, info_ptr);
  1565.  
  1566.   /* Allocate row buffers for the input */
  1567.   row_ptrs = (png_byte **)POV_MALLOC(height*sizeof(png_byte *), "PNG image");
  1568.   
  1569.   for (row = 0; row < height; row++)
  1570.   {
  1571.     row_ptrs[row] = (png_byte *)POV_MALLOC(r_info_ptr->rowbytes, "PNG image line");
  1572.   }
  1573.   
  1574.   /* Read in the entire image */
  1575.   png_read_image(r_png_ptr, row_ptrs);
  1576.   
  1577.   /* We must copy all the values because PNG supplies RGBRGB, but POV-Ray
  1578.    * stores RGB components in separate arrays
  1579.    */
  1580.   for (row = 0; row < height; row++)
  1581.   {
  1582.     if (Image->Colour_Map == NULL)
  1583.     {
  1584.       line_data = &Image->data.rgb_lines[row];
  1585.  
  1586.       line_data->red = (unsigned char *)POV_MALLOC(width, "PNG image line");
  1587.       line_data->green = (unsigned char *)POV_MALLOC(width, "PNG image line");
  1588.       line_data->blue = (unsigned char *)POV_MALLOC(width, "PNG image line");
  1589.  
  1590.       if (r_info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  1591.       {
  1592.         line_data->transm = (unsigned char *)POV_MALLOC(width,"PNG image line");
  1593.       }
  1594.       else
  1595.       {
  1596.         line_data->transm = NULL;
  1597.       }
  1598.       
  1599.       /* 8-bit grayscale image with a full alpha channel. Since the paletted
  1600.        * images don't support different transparencies for each pixel, we
  1601.        * have to make this a full-color image.
  1602.        */
  1603.       if (r_info_ptr->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  1604.           r_info_ptr->bit_depth <= 8)
  1605.       {
  1606.         for (col = j = 0; col < width; col ++, j += stride)
  1607.         {
  1608.           line_data->red[col] =
  1609.           line_data->green[col] =
  1610.           line_data->blue[col] = row_ptrs[row][j];
  1611.           line_data->transm[col] = 255 - row_ptrs[row][j + 1];
  1612.         }
  1613.       }
  1614.       /* For 16 bit PNG heightfields, we need to know if the map will be used
  1615.        * for an image (in which case we want to store the values as grays, or
  1616.        * if we want to use it as a heightfield (in which case we need to store
  1617.        * it in the MSB-read, LSB-green format that POV uses to store 16-bit
  1618.        * heightfields.
  1619.        */
  1620.       else if ((r_info_ptr->color_type & PNG_COLOR_MASK_COLOR) ==
  1621.                                                           PNG_COLOR_TYPE_GRAY)
  1622.       {
  1623.         if (Image->Image_Type & HF_FTYPE)
  1624.         {
  1625.           for (col = j = 0; col < width; col ++, j += stride)
  1626.           {
  1627.             int red = row_ptrs[row][j];
  1628.             int green = row_ptrs[row][j + 1];
  1629.  
  1630.             line_data->red[col] = red;
  1631.             line_data->green[col] = green;
  1632.             line_data->blue[col] = 0;
  1633.  
  1634.             if (r_png_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  1635.             {
  1636.               line_data->transm[col] = 255 - row_ptrs[row][j + 2];
  1637.             }
  1638.           }
  1639.         }
  1640.         else
  1641.         {
  1642.           for (col = j = 0; col < width; col ++, j += stride)
  1643.           {
  1644.             int red = row_ptrs[row][j];
  1645.   
  1646.             line_data->red[col] = red;
  1647.             line_data->green[col] = red;
  1648.             line_data->blue[col] = red;
  1649.  
  1650.             if (r_png_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  1651.             {
  1652.               line_data->transm[col] = 255 - row_ptrs[row][j + 2];
  1653.             }
  1654.           }
  1655.         }
  1656.       }
  1657.       else /* r_info_ptr->color_type & PNG_COLOR_MASK_COLOR */
  1658.       {
  1659.         for (col = j = 0; col < width; col ++, j += stride)
  1660.         {
  1661.           line_data->red[col] = row_ptrs[row][j];
  1662.           line_data->green[col] = row_ptrs[row][j + 1];
  1663.           line_data->blue[col] = row_ptrs[row][j + 2];
  1664.  
  1665.           if (r_png_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  1666.           {
  1667.             line_data->transm[col] = 255 - row_ptrs[row][j + 3];
  1668.           }
  1669.         }
  1670.       }
  1671.       POV_FREE(row_ptrs[row]);
  1672.     }
  1673.     else
  1674.     {
  1675.       Image->data.map_lines[row] = row_ptrs[row];
  1676.     }
  1677.   }
  1678.  
  1679.   /* Clean up the rest of the PNG memory and such */
  1680.  
  1681.   POV_FREE(row_ptrs);
  1682.  
  1683.   /* read the rest of the file, getting any additional chunks in png_info */
  1684.  
  1685.   png_read_end(r_png_ptr, r_info_ptr);
  1686.  
  1687.   /* clean up after the read, and free any memory allocated */
  1688.  
  1689.   png_destroy_read_struct(&r_png_ptr, &r_info_ptr, (png_infopp)NULL);
  1690.  
  1691.   fclose(filep);
  1692. }
  1693.